<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen v-model="showDialog" :title="title">
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-addRow>
                <el-button :disabled="props.orderId" @click="addRow"
                  >新增行</el-button
                >
              </template>
              <template v-slot:filter-removeProduct>
                <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                  >删除行</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <!-- 表格 -->
              <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
                <page-table
                  ref="table"
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tabIndex="false"
                  :check-box="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-businessDate="scope">
                    <el-form-item
                      class="margin-bottom"
                      :prop="`data.${scope.$index}.businessDate`"
                      :rules="[
                        {
                          required: scope.$index >= 0,
                          message: '请输入日期',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-date-picker
                        v-model="scope.row.businessDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择日期"
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-assetCode="scope">
                    <el-form-item
                      class="margin-bottom"
                      :prop="`data.${scope.$index}.assetCode`"
                      :rules="[
                        {
                          required: scope.$index >= 0,
                          message: '请选择资产卡片',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        :ref="'batchRef' + scope.$index"
                        :disabled="true"
                        class="not-mongolia"
                        placeholder="资产卡片号"
                        v-model="scope.row.assetCode"
                      >
                        <template #append>
                          <div
                            class="el-input-search"
                            @click="addAsset(scope.row, scope.$index)"
                          >
                            <el-icon style="vertical-align: middle">
                              <MoreFilled />
                            </el-icon>
                          </div>
                        </template>
                      </el-input>
                    </el-form-item>
                  </template>
                  <template v-slot:col-amount="scope">
                    <el-form-item
                      class="margin-bottom"
                      v-if="scope.row.assetCode"
                    >
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item">
                            <el-form-item
                              :prop="`data.${scope.$index}.amount`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: validatorProportion,
                                        rowData: scope.row,
                                        trigger: 'blur',
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input-number
                                style="width: 100%"
                                v-model.lazy="scope.row.amount"
                                clearable
                                controls-position="right"
                                :precision="3"
                                @change="changeLarge($event)"
                                :min="0.001"
                              />
                            </el-form-item>
                          </div>
                        </div>
                      </div>
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 添加资产 -->
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      table-key="analysisPlanAddCoreAsset-com.slip.spd.entity.vo.core.CoreAssetVO"
      :check-box="!orderId"
      :highlightRow="true"
      @callback="callBackAsset"
    />
  </div>
</template>

<script setup name="analysisRepairModify">
import {
  addAnalysisRepair,
  updateAnalysisRepair,
  getAnalysisRepairDetail,
} from '@/api/asset'
import _ from 'lodash'
const { proxy } = getCurrentInstance()
const emit = defineEmits()
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))

const props = defineProps({
  visible: {
    type: Boolean,
  },
  title: {
    type: String,
  },
  orderId: {
    type: [Number, String],
  },
})
const validatorProportion = (rule, value, callback) => {
  if (!value) {
    return callback('请输入维修费用')
  } else {
    callback()
  }
}
const selectAssetInfo = ref({
  visible: false,
  query: {
    queryMap: {
      assetStatus: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1,3',
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3,4,5,6',
      },
    },
    queryParams: { assetAnalysisFilter: 0, analysisDeptAuth: 1 },
  },
})
// 过滤相关配置
const filterInfo = reactive({
  query: {},
  list: [
    { type: 'slot', value: 'addRow' },
    { type: 'slot', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  sysGroup: [],
  productSysGroup: [],
  data: [
    {
      businessDate: '',
      assetCode: '',
      id: new Date().getTime() + (1 + Math.random()),
    },
  ],
  tabList: [],
  tabIndex: 0,
  selections: [],
  fieldList: [
    {
      label: '日期',
      value: 'businessDate',
      type: 'slot',
      minWidth: '100px',
    },
    {
      label: '资产卡片号',
      align: 'left',
      value: 'assetCode',
      type: 'slot',
      minWidth: '150px',
    },
    {
      label: '资产名称',
      value: 'assetName',
    },
    {
      label: '规格',
      value: 'standard',
    },
    {
      label: '厂家',
      value: 'brandName',
    },
    {
      label: '维修费用',
      value: 'amount',
      type: 'slot',
      width: '160px',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '删除行',
        event: removeBatch,
        show: !props.orderId,
      },
    ],
  },
})

const formRefs = ref([])
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.value.data.length
})

const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length && !props.orderId
})

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm']]
  if (props.orderId) {
    getMain()
  }
})
function getMain() {
  getAnalysisRepairDetail({
    id: props.orderId,
    assetAnalysisFilter: 0,
  }).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
    }
  })
}
function callBackAsset(data) {
  data.forEach((item, index) => {
    item.assetId = data.id
    if (index === 0) {
      tableInfo.value.data[selectAssetInfo.value.index] = {
        ...selectAssetInfo.value.row,
        ...item,
      }
    } else {
      tableInfo.value.data.splice(selectAssetInfo.value.index + index, 0, item)
    }
  })
  // selectAssetInfo.value.row.assetCode = data.assetCode
  // tableInfo.value.data[selectAssetInfo.value.index] = {
  //   ...selectAssetInfo.value.row,
  //   ...data,
  // }
  // tableInfo.value.data[selectAssetInfo.value.index].assetId = data.id
}
//新增行
function addRow(row, index = '') {
  console.log(index)
  let obj = {
    businessDate: '',
    assetCode: '',
    id: new Date().getTime() + (1 + Math.random()),
  }
  if (index || index === 0) {
    tableInfo.value.data.splice(index + 1, 0, obj)
  } else {
    tableInfo.value.data.push(obj)
  }
}

function addAsset(row, index) {
  selectAssetInfo.value.row = row
  selectAssetInfo.value.index = index
  selectAssetInfo.value.visible = true
}

function changeLarge(e) {
  tableInfo.value.data.forEach((item, index) => {
    proxy.$refs.tableForm.clearValidate(`data.${index}.amount`)
  })
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}

function removeProduct() {
  tableInfo.value.data = tableInfo.value.data.filter(
    (item) => !tableInfo.value.selections.includes(item)
  )
  if (!tableInfo.value.data.length) {
    tableInfo.value.data = [
      {
        businessDate: '',
        assetCode: '',
        id: new Date().getTime() + (1 + Math.random()),
      },
    ]
  }
}
//删除行
function removeBatch(row, index) {
  tableInfo.value.data = tableInfo.value.data.filter((element) => {
    return element.id != row.id
  })
}

// 触发事件
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let list = tableInfo.value.data.map((item) => {
      let params = {
        amount: item.amount,
        assetId: props.orderId ? item.assetId : item.id,
        businessDate: item.businessDate,
      }
      if (props.orderId) {
        params.id = props.orderId
      }
      return params
    })
    const api = props.orderId ? updateAnalysisRepair : addAnalysisRepair
    api(list).then((res) => {
      if (res && res.success) {
        showDialog.value = false
        emit('returnModify')
      }
    })
  })
}
</script>

<style scoped lang="scss">
.el-input-search {
  width: 100%;
  height: 100%;
}
</style>
